package com.linsen.oss.service.impl;

import cn.hutool.core.io.FileUtil;
import com.linsen.oss.props.FileProperties;
import com.linsen.oss.service.FileService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final FileProperties fileProperties;

    @Override
    public String uploadFile(MultipartFile multipartFile,String userId) {
        String folder = fileProperties.getPath() + File.separator;
        if(!FileUtil.exist(folder)){
            FileUtil.mkdir(folder);
        }
        // 文件名
        String fileName = multipartFile.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = userId+"-"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS")) + suffixName;
        String path = folder + newFileName;
        File file = new File(path);
        if(FileUtil.exist(file)){
            throw new RuntimeException();
        }
        try {
            File file1 = FileUtil.writeBytes(multipartFile.getBytes(), path);
            if(file1.length() < 0){
                throw new RuntimeException();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileProperties.getHost() + File.separator + newFileName;
    }

    @Override
    public File getNetFile(String url){
        String host = fileProperties.getHost();
        String path = fileProperties.getPath();

        if(url.contains(host)){
            return new File(url.replace(host, (path + "/")));
        }else{
            try {
                InputStream inputStream = new URL(url).openStream();
                File image = File.createTempFile("image", "");
                FileUtils.copyInputStreamToFile(inputStream,image);
                return image;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    @Override
    public void deleteNetFile(String url,File file) {
        String host = fileProperties.getHost();

        if(!url.contains(host)){
            file.delete();
        }
    }
}
